package com.wjwframework.jfinal.web.model;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.plugin.activerecord.Record;
import com.wjw.utils.GUID;
import com.wjw.utils.RegExpUtil;
import com.wjw.utils.sms.Sms;
import com.wjw.utils.sms.SmsClientHywx;
import com.wjwframework.jfinal.config.BaseConfig;
import com.wjwframework.jfinal.model.BaseModelImpl;
import com.wjwframework.jfinal.model.CommonDbUtil;
import com.wjwframework.jfinal.vo.PageNavation;
import com.wjwframework.jfinal.vo.Response;
import com.wjwframework.jfinal.web.model.base.BaseSysSms;

/**
 * @className 系统短信表
 * @description 
 * @author wjw
 * @cTime 2016年6月8日上午10:17:43
 */
public class SysSms extends BaseSysSms<SysSms> implements BaseModelImpl{

	private static final long serialVersionUID = -8754694903517332625L;

	public static final SysSms dao=new SysSms();
	
	public static Long expireTime=1800L;//30分钟验证码过期时间
	
	/**
	 * 判断是否已发送验证码，如果不等于null则表示已经发过验证码,并有效
	 * @param phone
	 * @return
	 */
	public static Record hasSendCode(final String phone,final String sms_model){
		Record result=null;
		String condition="phone=? AND expired=? ORDER BY ctime DESC";
		Record phoneMsg=dao.getCommDbUtil().findFirst(condition,phone,0);
		if(phoneMsg!=null){
			long btTime = phoneMsg.getDate("ctime").getTime()- (new Date().getTime());//计算过期时间
			if(Math.abs(btTime)>expireTime*1000){//code创建时间与当前时间相差大于120秒
				dao.getCommDbUtil().updateSet("expired=1","request_id=?",phoneMsg.getStr("request_id"));
			}else{
				String content=String.format(sms_model, phoneMsg.getStr("code"));
				//发送短信
				SmsClientHywx smsClient = new SmsClientHywx();
				Sms sms = new Sms(phone, content, phoneMsg.getStr("code"), "system", phone);
				smsClient.send(sms);
				result=phoneMsg;
			}
		}
		return result;
	}
	
	/**
	 * 注册创建验证码。发送验证码之前判断是否已经发过验证，如果已经发过，则不会再发，否则会发送验证码
	 * @param phone
	 * @return
	 */
	public static Response sendRegisterCode(final String phone){
		Response response=new Response();
		String requestId=null;
		Record result=hasSendCode(phone,Sms.defaultTemplate);
		if(result!=null){
			response.setErrcode(0);
			response.result.put("request_id",result.get("request_id"));
			return response;
		}
		String code = Sms.createCode();
		String content=String.format(Sms.defaultTemplate, code);
		//发送短信
		SmsClientHywx smsClient = new SmsClientHywx();
		Sms sms = new Sms(phone, content, code, "system", phone);
		smsClient.send(sms);
		
		//将发送的短信内容保存到数据库
		requestId=GUID.create();//生产请求唯一码
		SysSms phoneMsg=new SysSms();
		phoneMsg.set("phone",phone)
		.set("content",content)
		.set("code",code)
		.set("request_id", requestId);
		if(phoneMsg.save()){
			response.setErrcode(0);
			response.result.put("request_id",requestId);
		}
		return response;
	}

	/**
	 * 重置密码验证码。发送验证码之前判断是否已经发过验证，如果已经发过，则不会再发，否则会发送验证码
	 * @param phone
	 * @return
	 */
	public static Response sendResetCode(final String phone){
		String sms_model=BaseConfig.baseProp.get("sms.code");
		Response response=new Response();
		String requestId=null;
		Record result=hasSendCode(phone,sms_model);
		if(result!=null){
			response.setErrcode(0);
			response.result.put("request_id",result.get("request_id"));
			return response;
		}
		String send_code = Sms.createCode();
		String content=String.format(sms_model, send_code);
		//发送短信
		SmsClientHywx smsClient = new SmsClientHywx();
		Sms sms = new Sms(phone, content, send_code, "system", phone);
		smsClient.send(sms);
		
		//将发送的短信内容保存到数据库
		requestId=GUID.create();//生产请求唯一码
		SysSms phoneMsg=new SysSms();
		phoneMsg.set("phone",phone)
		.set("content",content)
		.set("code",send_code)
		.set("request_id", requestId);
		if(phoneMsg.save()){
			response.setErrcode(0);
			response.result.put("request_id",requestId);
		}
		return response;
	}
	
	/**
	 * 判断验证码是否正确
	 * @param code
	 * @return
	 */
	public boolean isCodeRight(String requestId,String code,String phone){
		boolean flag=false;
		if(StringUtils.length(code)==6&&RegExpUtil.isNumeric(code)){
			String condition="request_id=? AND code=? AND expired=? AND phone=?";
			Record record=dao.getCommDbUtil().findFirst(condition,requestId,code,0,phone);
			if (record!=null) {
				long btTime=(record.getDate("ctime").getTime())-(new Date().getTime());
				dao.getCommDbUtil().updateSet("expired=1",condition,requestId,code,0,phone);
				if(Math.abs(btTime)<expireTime*1000){//code创建时间与当前时间相差小于30分钟
					flag=true;
				}
			}
		}
		return flag;
	}
	
	@Override
	public CommonDbUtil getCommDbUtil() {
		return new CommonDbUtil(getClass());
	}

	@Override
	public boolean deleteByIds(String ids) {
		return true;
	}

	@Override
	public PageNavation findList(PageNavation page) {
		// TODO Auto-generated method stub
		return null;
	}
}